 //
//  CLChatViewController.m
//  chanlin
//
//  Created by Ryan on 15/6/7.
//  Copyright (c) 2015年 chanlin. All rights reserved.
//

#import "CLChatViewController.h"
#import "IFCoreDataManager.h"
#import "CLLive.h"
#import "CLLiveCell.h"
#import "CLComentDataModel.h"
#import "CLPushAnimatedRight.h"
#import "CLLoginInViewController.h"
#import "CLLiveViewController.h"
#import "SgrWeakTarget.h"
#import "SgrGCD.h"

@implementation CLChatViewController


- (instancetype)init{
    self=[super init];
    if(self){
        
        
    }
    return self;
}

- (NSString *)topicId{
    return self.dataModel.topciId;
}

- (void)setFrame:(CGRect)frame{
    self.view.frame=frame;
    self.tableView.height=self.view.height;
}


- (void)viewDidLoad{
    [super viewDidLoad];
    self.tableView.frame=self.view.bounds;
    [self.tableView setAutoLoadingNext:NO];
    
    self.dataModel=[[CLLiveDataModel alloc] initWithId:self.liveId];
    self.dataModel.titlestr=self.titlestr;
    self.dataModel.room=self.room;
    
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES];
    NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"CLLive"];
    req.predicate = [NSPredicate predicateWithFormat:@"room=%@ and liveId==%@", @(self.room),self.liveId];
    req.sortDescriptors = @[sort];
    self.fetch = [[NSFetchedResultsController alloc] initWithFetchRequest:req
                                                     managedObjectContext:[IFCoreDataManager sharedInstance].mainMoc
                                                       sectionNameKeyPath:nil
                                                                cacheName:nil];
    self.fetch.delegate=self;
    [self.fetch performFetch:nil];
    
    if([self isViewLoaded])
        [self reloadTable];

    
    __weak typeof(self) me=self;
    
    [self.dataModel reflashData:^(BOOL success, id responseObj, NSString *message) {
        [me.tableView stopHeadLoading];
        if(success)me.page=1;
        if(success){
            [me createTimer];
        }
        
    }];
    
    
}

- (void)createTimer{
    SgrWeakTarget *target=[[SgrWeakTarget alloc] init];
    target.obj=self;
    target.select=@selector(checkProgress);
    
    self.timer=[NSTimer scheduledTimerWithTimeInterval:10 target:target selector:@selector(perform) userInfo:nil repeats:YES];
}

- (void)checkProgress{
    [self checkReflahs];
}

-(void)jTableViewStartHeadLoading:(JTableView *)tableView{
    __weak typeof(self) me=self;
    [self.dataModel reflashData:^(BOOL success, id responseObj, NSString *message) {
        [me.tableView stopHeadLoading];
        if(success)me.page=1;
    }];
}


- (void)checkReflahs{
    if(self.tableView.contentOffset.y<50){
        __weak typeof(self) me=self;
        [self.dataModel reflashData:^(BOOL success, id responseObj, NSString *message) {
            [me.tableView stopHeadLoading];
            if(success)me.page=1;
        }];
    }
}


- (void)jTableViewStartBottomMoreLoading:(JTableView *)tableView{
    __weak typeof(self) me=self;
  
    [self.dataModel reflashNextPage:self.page+1
                                   :self.fetch.fetchedObjects.lastObject
                                   :^(BOOL success, id responseObj, NSString *message) {
                                       if(success){
                                           me.page++;
                                       }
                                       [me.tableView stopBottomMoreWithScuessLoading];
    }];

}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 44.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height=0;
    CLLive *live=[self.fetch objectAtIndexPath:indexPath];
    if(self.room==1){
        height+=12.f;
        height+=15.f;
        height+=12.f;
        height+=live.titleHeight;
        if(live.titleHeight>0){
            height+=12.f;
        }
        if(_isStrNotNull(live.img)){
            height+=172.f;
            height+=12.f;
        }
        if(live.contentHeight>0){
            height+=live.contentHeight;
            height+=12.f;
        }
        
        height+=16.f;
        height+=12.f;
        height+=12.f;
        
        if(_isStrNotNull(live.replyname)){
            height+=24+live.replycHeight+13+12+12;
        }
    }else if(self.room==2){
        height+=12.f;
        height+=15.f;
        height+=12.f;
   
 
        if(live.contentHeight>0){
            height+=live.contentHeight;
            height+=12.f;
        }
        
        height+=16.f;
        height+=12.f;
        height+=12.f;
        if(_isStrNotNull(live.replyname)){
            height+=24+live.replycHeight+13+12+12;
        }


    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
     CLLive *live=[self.fetch objectAtIndexPath:indexPath];
     static NSString *cellId=@"CLLiveCell";
    CLLiveCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell=[[CLLiveCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.chat=self;
    }
    cell.path=indexPath;
    [cell load:live];
    
    
    return cell;
}

- (void)support:(NSIndexPath *)indexPath{
    CLLive *live=[self.fetch objectAtIndexPath:indexPath];
    NSManagedObjectID *oid=live.objectID;
    NSString *setId=[NSString stringWithFormat:@"%@%@",_safeStr(self.liveId) ,_safeStr(live.cmtId)];
//    if([[CLGloble sharedInstance].supports containsObject:setId]){
//        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"已经点赞过"];
//        return;
//    }
    
    
    CLLiveCell *cell=(CLLiveCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    
    
   
    
    __weak typeof(self) me=self;
    [[CLComentDataModel sharedInstance] support:self.topicId
                                      commentID:live.cmtId
                                          block:^(BOOL success, NSString *responseStr) {
                                              if(success){
                                                  cell.support.hidden=YES;
                                                  [[CLGloble sharedInstance].supports addObject:_safeStr(setId)];
                                                  
                                                  
                                                  
                                                  CGRect frame= [cell.baseView convertRect:cell.support.frame toView:[[CLGloble sharedInstance] getMainWindow]];
                                                  UIView *animationView = [[UIView alloc]initWithFrame:frame];
                                                  animationView.backgroundColor = [UIColor clearColor];
                                                  
                                                  [[[CLGloble sharedInstance] getMainWindow] addSubview:animationView];
                                                  
                                                  CALayer *layer = [CALayer layer];
                                                  layer.frame = animationView.bounds;
                                                  layer.contentsGravity = kCAGravityResizeAspect;
                                                  layer.contents = (id)[UIImage imageNamed:@"comment_replay_supported.png"].CGImage;
                                                  
                                                  
                                                  [[animationView layer] addSublayer:layer];
                                                  
                                                  
                                                  [UIView animateWithDuration:0.2
                                                                   animations:^{
                                                                       
                                                                       CGRect frame = animationView.frame;
                                                                       frame.origin.x-= 6;
                                                                       frame.origin.y -= 22;
                                                                       frame.size.width+=12;
                                                                       frame.size.height+=12;
                                                                       animationView.frame=frame;
                                                                       
                                                                   }
                                                                   completion:^(BOOL finished){
                                                                       
                                                                       
                                                                       [[SgrGCD sharedInstance] enqueueForeground:^{
                                                                           
                                                                           [CATransaction begin];
                                                                           
                                                                           [CATransaction setCompletionBlock:^{
                                                                               [CATransaction begin];
                                                                               [CATransaction setAnimationDuration:0.8];
                                                                               [CATransaction setCompletionBlock:^{
                                                                                   cell.support.hidden=NO;
                                                                                   [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
                                                                                    CLLive *live1=(CLLive *)   [CLLive managerObjWithObjectID:oid];
                                                                                       live1.support+=1;
                                                                                       
                                                                                       [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                                                                                   }];
                                                                                   
                                                                                   
                                                                                   [animationView removeFromSuperview];
//                                                                                    [me.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                                                                               }];
                                                                               layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 360.0f, 0.0f, 1.0f,0.0f);
                                                                               
                                                                               [CATransaction commit];
                                                                           }];
                                                                           
                                                                           [CATransaction setAnimationDuration:0.8];
                                                                           layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 1.0f,0.0f);
                                                                           
                                                                           [CATransaction commit];
                                                                           
                                                                       }];
                                                                   }];

                                                  
                                                 
                                                  [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"点赞成功"];
                                              }
                                          }];
}
- (void)thecopy:(NSIndexPath *)indexPath{
    CLLive *live=[self.fetch objectAtIndexPath:indexPath];
    NSString *text=live.content;
    if(_isStrNotNull(text)){
        UIPasteboard *pasted=[UIPasteboard generalPasteboard];
        pasted.string=text;
        [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"内容复制成功"];
    }
}
- (void)reply:(NSIndexPath *)indexPath{
    
    if(![[CLGloble sharedInstance] isLogin]){
        
        CLLoginInViewController *login=[[CLLoginInViewController alloc] init];
        [[CLPushAnimatedRight sharedInstance] pushController:login];
        return ;
    }

    CLLive *live=[self.fetch objectAtIndexPath:indexPath];
    
    NSString *str=[NSString stringWithFormat:@"%@#-%d#-%@",_safeStr(live.nickName),live.room ,_safeStr(live.content)];
    [self.parent replay:str];
    
       
}
@end
